#! /usr/bin/bash

#服务器ip
HOST_IP=$1

if [[ -z $HOST_IP ]]; then
    echo 'usage: bash clear-user-cache ${YOUR-IP}'
    return 1
fi

if ! type jq >/dev/null; then
    echo please install jq
    return 1
fi

# 获取token地址
TOKEN_URI="https://$HOST_IP/auth/realms/master/protocol/openid-connect/token"
# get token
access_token=$(curl -Ssk -X POST "$TOKEN_URI" \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode "username=TmytcJ9S" \
    --data-urlencode "password=Inspur1!" \
    --data-urlencode 'grant_type=password' \
    --data-urlencode 'client_id=admin-cli' | jq -r .access_token)

if [[ -z $access_token ]]; then
    echo fetch access_token failed, retry plz
    return 1
fi
echo "got access token success"

state=$(curl -Ssk -w %{http_code} "https://$HOST_IP/auth/admin/realms/master/clear-user-cache" \
    -H "authorization: Bearer $access_token" \
    --data-raw '{"realm":"master"}')

if [[ $state -eq 204 ]]; then
    echo clear user cache success
fi
